<?php

/**
 * Created by PhpStorm.
 * User: evan
 * Date: 16/9/1
 * Time: 下午6:38
 */
class Base extends MY_Admin_Controller
{
    public function index()
    {
    	$page = intval($this->input->get_post('page'));
    	$page = $page ? $page : 1;
    	
    	$uid = intval($this->input->get_post('uid'));
    	$start_time = trim($this->input->get_post('start_time'));
    	$end_time = trim($this->input->get_post('end_time'));
    	
    	$where = array();

        (isset($_GET['status']) && $_GET['status'] >= 0) && $where['status'] = $_GET['status'];
        $uid && $where['anchor_uid'] = $uid;
        $start_time && $where['create_time>'] = $start_time;
        $end_time && $where['create_time>'] = $start_time;

    	
    	$this->load->model('direct_seeding/Model_direct_seeding','direct');
    	$total_rows = $this->direct->count($where);
    	
    	//分页
    	$this->load->library('pagination');
    	 
    	$config['total_rows'] = $total_rows;
    	$config['per_page'] = 20;
    	$config['base_url'] = '/direct_seeding/Base/index';
    	 
    	$this->pagination->initialize($config);
    	$show_page = $this->pagination->create_links();
    	
    	$offset = ($page-1) * $config['per_page'];
    	
        //直播列表
        $directInfo = $this->direct->lists($offset,  $config['per_page'], $where);

        //竞拍分类列表
        $this->load->model('auction/Model_auction_cate','cate');
        $cateInfo = $this->cate->getAllLists();

        //图片列表
        $this->load->model('common/Model_file','file');
        $fileInfo = $this->file->getByIn('fid', array_column($directInfo, 'cover'));


        //主副播用户信息
        $auction_uids = array_column($directInfo, 'auction_uid');
        $anchor_uids  = array_column($directInfo, 'anchor_uid');
        $this->load->model('user/Model_user', 'u');
        $user_data = $this->u->getByIn('uid', array_merge($auction_uids, $anchor_uids));


        //竟拍信息
        $aids = array_column($directInfo, 'aid');
        $this->load->model('auction/Model_auction', 'a');
        $auction_data = $this->a->getByIn('aid', $aids);


        $this->load->model('direct_seeding/Model_direct_seeding_video_link', 'dsvl');
        foreach ($directInfo as $k => $v)
        {
            $is_playback = (int)$this->dsvl->is_playback($v['ds_id']);
            $directInfo[$k]['is_playback'] = $is_playback ? DIRECT_SEEDING_IS_PLAYBACK_YES : DIRECT_SEEDING_IS_PLAYBACK_NOT;
        }

        /*
        $ds_ids = array_column($directInfo, 'ds_id');
        $this->load->model('direct_seeding/Model_direct_seeding_video_link', 'dsvl');
        $video_link = $this->dsvl->getByIn('ds_id', $ds_ids, array('status' => DIRECT_SEEDING_IS_PLAYBACK_YES));


        foreach ($directInfo as $k => $v)
        {
            foreach ($video_link as $lk => $lv)
            {
                if ($v['ds_id'] == $lv['ds_id'])
                {
                    $directInfo[$k]['video_link'][] = $lv;
                    unset($video_link[$lk]);
                }
            }
        }
        //*/


        $data = array
        (
            'directInfo' => $directInfo,
            'cateInfo'   => $cateInfo,
            'fileInfo'   => $fileInfo,
        	'show_page'  => $show_page,
        	'user_data'  => $user_data,
        	'auction_data' => $auction_data,
        	'total_rows' => $config['total_rows'],
        );

        $this->load->view('admin/direct_seeding/base/index',$data);
    }
    
    public function usages_cost()
    {
    	$start_time = trim($this->input->get_post('start_time'));
    	$end_time = trim($this->input->get_post('end_time'));
    	
    	$this->load->library('rtc/RTCApi');
    	$RTCApi = new RTCApi();
    	
    	$data = $RTCApi->usages($start_time, $end_time);
    
    	$this->load->view('admin/direct_seeding/base/usages_cost', $data);
    }
    
    public function bypass_cost()
    {
    	$start_time = trim($this->input->get_post('start_time'));
    	$end_time = trim($this->input->get_post('end_time'));
    	 
    	$this->load->library('rtc/RTCApi');
    	$RTCApi = new RTCApi();
    	
    	$data = $RTCApi->bypass_usage($start_time, $end_time);
    
    	$this->load->view('admin/direct_seeding/base/bypass_cost', $data);
    }


    public function monitor()
    {
    	//直播列表
    	
    	$where = array
    	(
            'status' => DS_STATUS_DOING,
    	);
    	
    	$this->load->model('direct_seeding/Model_direct_seeding','direct');
    	$list = $this->direct->getAllLists($where);


    	$data = array
        (
            'list' => $list
    	);
    
    	$this->load->view('admin/direct_seeding/base/monitor', $data);
    }
    
    public function close()
    {
    	$response = array('code' => '0', 'msg' => '操作成功');
    	
    	$ds_id = (int)$this->input->get_post('ds_id');
    	 
    	//判断直播是否存在
        $this->load->model('direct_seeding/Model_direct_seeding', 'ds');
        $ds_item = $this->ds->getById($ds_id);
        if (empty($ds_item))
        {
        	$response = error(120002);
            $this->json_output($response);
        }
        
        
        if($ds_item['status'] != DS_STATUS_DOING)
        {
        	$response = error(120015);
            $this->json_output($response);
        }
        
        $this->load->model('direct_seeding/Model_direct_seeding_join_log', 'dsjl');
        $join_num = $this->dsjl->count(array('ds_id' => $ds_id), 'uid');
        
        $duration = time()-strtotime($ds_item['real_start_time']);
        $duration = $duration>0 ? $duration:0;
        
    	$item = array
    	(
    			'real_duration' => ceil($duration/60),
    			'join_num'      => $join_num,
    			'status'        => DS_STATUS_ABNORMAL,
    			'end_type'      => DIRECT_SEEDING_END_PLATFORM,
    	);
    	$this->ds->save($item, $ds_id);
    
    	$direct_seeding_end['duration']   = gmstrftime('%H:%M:%S', $duration);
    	$direct_seeding_end['join_num']   = $join_num;
    	
    	$this->load->service('message/service_message_im');
     	$data = array(
     				'chat_room_num' => $ds_item['chat_room_num'],
     				'content' => '@MSMK@GROUP_CHAT_ROOM_DELETE@'.$direct_seeding_end['duration'].'aa668888866aa'.$direct_seeding_end['join_num'].'aa668888866aa0aa668888866aa0',
     			);
     	$send_rs = $this->service_message_im->group_send($data);
     	
     	if($send_rs['status'] != 200)
     	{
     		$response = error($send_rs['status']);
            $this->json_output($response);
     	}

        $this->json_output($response);
    }
    
    
    public function warning()
    {
    	$response = array('code' => '0', 'msg' => '操作成功');
    	 
    	$ds_id = (int)$this->input->get_post('warning_ds_id');
    	$warning_object = (int)$this->input->get_post('warning_object');
    	$warning_text = $this->input->get_post('warning_text');
    	
    	
    	//判断直播是否存在
    	$this->load->model('direct_seeding/Model_direct_seeding', 'ds');
    	$ds_item = $this->ds->getById($ds_id);
    	if (empty($ds_item))
    	{
    		$response = error(120002);
            $this->json_output($response);
    	}
    	
    	
    	if($ds_item['status'] != DS_STATUS_DOING)
    	{
    		$response = error(120015);
            $this->json_output($response);
    	}
    	
    	
    	if($warning_object == 1)
    	{
    		$content = '@MSMK@DIRECT_SEEDING_WARNING_ANCHOR@';
    	}else{
    		$content = '@MSMK@DIRECT_SEEDING_WARNING_AUCTION@';
    	}
    	
    	$content .= $warning_text;
    
    	$this->load->service('message/service_message_im');
    	$data = array(
    			'chat_room_num' => $ds_item['chat_room_num'],
    			'content' => $content,
    	);
    	$send_rs = $this->service_message_im->group_send($data);
    	
    	if($send_rs['status'] != 200)
    	{
    		$response = error($send_rs['status']);
            $this->json_output($response);
    	}

        $this->json_output($response);
    }

    /*
    *  直播页面修改浏览
     * */
    public function create()
    {
        $ds_id = (int)$this->uri->segment(4);

        //直播
        $this->load->model('direct_seeding/Model_direct_seeding', 'direct');
        $directInfo = $this->direct->getById($ds_id);

        //竞拍分类列表
        $this->load->model('auction/Model_auction_cate','cate');
        $cateInfo = $this->cate->getById($directInfo['cid']);

        //图片信息
        $this->load->model('common/Model_file','file');
        $fileInfo = $this->file->getById($directInfo['cover']);

        $data = array(
            'directInfo'        =>    $directInfo,
            'cateInfo'          =>    $cateInfo,
            'fileInfo'          =>    $fileInfo
        );

        $this->load->view('admin/direct_seeding/base/create',$data);
    }

    /*
    * 开播资料编辑后保存
    * 竞拍相关信息不能在此模块设置，开播时间在竞拍物品内设置，直播状态需更新到对应的竞拍物品内
    **/
    public function save()
    {
        $ds_id = (int)$this->input->get_post('ds_id');
        $aid = (int)$this->input->get_post('aid');

        $data = array
        (
            'duration'        => (int)trim($this->input->get_post('duration')),
            'real_duration'   => (int)trim($this->input->get_post('real_duration')),
            'join_num'        => (int)trim($this->input->get_post('join_num')),
        	'expect_join_num' => (int)trim($this->input->get_post('expect_join_num')),
            'share_num'       => (int)$this->input->get_post('share_num'),
            'like_num'        => (int)$this->input->get_post('like_num'),
            'status'          => (int)$this->input->get_post('status'),
            'verify'          => $this->input->get_post('verify'),
            'end_type'        => (int)$this->input->get_post('end_type'),
            //判断是否选择图片如果选择了图片则获取新突破地址或者判断是新建页面还是修改页面
            'cover'           => !empty($_FILES['up_file']['tmp_name'])?$this->uploadFile('up_file'):(isset($ds_id)?$this->input->get_post('cover'):''),
            'sort'            => (int)$this->input->get_post('sort'),
        );

        //直播状态未结束时，结束方式为未结束
        if($data['status'] != 1){
            $data['end_type'] = 0;
        }

        $data_auction = array(
            'ds_status' => (int)$this->input->get_post('status'),
        );


        $this->load->model('auction/Model_auction', 'auction');
        if($this->auction->is_exist($aid)){
            //更新竞拍表的状态,需判断aid是否存在竞拍表内
            $this->auction->save($data_auction, $aid ? $aid : null);

            //更新直播表
            $this->load->model('direct_seeding/Model_direct_seeding', 'direct');
            $this->direct->save($data, $ds_id ? $ds_id : null);

            $this->load->helper('url');
            redirect(url('admin').'direct_seeding/base/index');
        }else{
            echo "<script>alert('保存失败')</script>";
        }

    }

    /*
      * 列表编辑审核保存
      *
      * */
    public function save_verify()
    {
        $ds_id = (int)$this->input->get_post('aid');

        $data = array(
            'verify'        =>      (int)$this->input->get_post('verify'),
        );

        //更新user_info表
        $this->load->model('direct_seeding/Model_direct_seeding', 'direct');

        $this->direct->save($data, $ds_id ? $ds_id : null);
        $response = array('code' => '1', 'msg' => '修改成功');

        $this->json_output($response);
    }

    /*
   * 弹幕列表
   * */
    public function barrage(){
        $ds_id = $this->uri->segment(4);

        $this->load->model('direct_seeding/Model_direct_seeding_barrage_log','barrage');

        $barrage = $this->barrage->lists(0,100000,array('ds_id'=>$ds_id));

        $this->load->model('direct_seeding/Model_direct_seeding', 'direct');

        $direct = $this->direct->getById($ds_id);


        $data = array(
            'barrage'      =>   array_values($barrage),
            'title'        =>   $direct['title']
        );

        $this->load->view('admin/direct_seeding/base/barrage',$data);
    }

    /*
   * 广告列表
   * */
    public function ad(){
        $ds_id = $this->uri->segment(4);

        $this->load->model('direct_seeding/Model_direct_seeding_ad_consume','ad');

        $ad_consume = $this->ad->lists(0,10000,array('ds_id'=>$ds_id));

        $this->load->model('direct_seeding/Model_direct_seeding', 'direct');

        $direct = $this->direct->getById($ds_id);

        $this->load->model('common/Model_advert_img', 'advert');

        $advert = $this->advert->getAllLists();


        $data = array(
            'ad_consume'   =>   array_values($ad_consume),
            'advert'       =>   $advert,
            'title'        =>   $direct['title']
        );

        $this->load->view('admin/direct_seeding/base/ad',$data);
    }


    /*
   * 参与人员列表
   * */
    public function join(){
        $ds_id = $this->uri->segment(4);

        $this->load->model('direct_seeding/Model_direct_seeding_join_log','join');

        $join = $this->join->lists(0,10000,array('ds_id'=>$ds_id));

        $this->load->model('direct_seeding/Model_direct_seeding', 'direct');

        $direct = $this->direct->getById($ds_id);

        $data = array(
            'join'         =>   array_values($join),
            'title'        =>   $direct['title']
        );

        $this->load->view('admin/direct_seeding/base/join',$data);
    }


    /**
     * 删除直播
     */
    public function delete()
    {
        $response = array('code' => '0', 'msg' => '操作成功');

        do {
            $ds_id = (int)$this->input->get_post('ds_id');

            if (!$ds_id)
            {
                $response = error(200010);
                break;
            }

            $this->load->model('direct_seeding/Model_direct_seeding', 'direct');
            $directInfo = $this->direct->getById($ds_id);

            //正在直播无法删除
            if($directInfo['status'] == 2)
            {
                $response = error(200011);
                break;
            }

            $res = $this->direct->delete(array('ds_id' => $ds_id));

            if (!$res)
            {
                $response = error(10080);
                break;
            }
        }while (false);


        $this->json_output($response);
    }


    public function income_count()
    {
        $response = array('code' => '0', 'msg' => '操作成功');


        do {
            $ds_id = (int)$this->input->get_post('ds_id');

            if (!$ds_id)
            {
                $response = error(200010);
                break;
            }


            $this->load->model('direct_seeding/Model_direct_seeding', 'ds');
            $item = $this->ds->getById($ds_id);
            if (empty($item))
            {
                $response = error(120002);
                break;
            }


            $this->load->service('finance/service_finance_tools');
            $ds_income = $this->service_finance_tools->ds_income($ds_id);


            if (200 != $ds_income['status'])
            {
                $response = error($ds_income['status']);
                break;
            }


            $this->load->model('direct_seeding/Model_direct_seeding_join_log', 'dsjl');
            $real_number = $this->dsjl->real_number($ds_id);
            if (200 != $real_number['status'])
            {
                $response = error($real_number['status']);
                break;
            }


            $ds_income['data']['real_number'] = $real_number['data']['number'];
            $response['data'] = $ds_income['data'];
        }while (false);


        $this->json_output($response);

    }


    public function playback_audit()
    {
        $response = array('code' => '200', 'msg' => '操作成功');


        do {
            $ds_id  = (int)$this->input->get_post('ds_id');
            $status = (int)$this->input->get_post('status');

            if (!$ds_id)
            {
                $response = error(200010);
                break;
            }


            if (!array_key_exists($status, config_item('direct_seeding_is_playback')))
            {
                $response = error(120044);
                break;
            }


            $this->load->model('direct_seeding/Model_direct_seeding', 'ds');
            $item = $this->ds->getById($ds_id);
            if (empty($item))
            {
                $response = error(120002);
                break;
            }


            $this->load->model('direct_seeding/Model_direct_seeding_video_link', 'dsvl');
            $rs = $this->dsvl->update(array('status' => $status), array('ds_id' => $ds_id));
            if (!$rs)
            {
                $response = error(50058);
                break;
            }

        }while (false);


        $this->json_output($response);
    }


    public function manual_liquidation()
    {
        $response = array('code' => '200', 'msg' => '操作成功');


        do {
            $ds_id  = (int)$this->input->get_post('ds_id');


            if (!$ds_id)
            {
                $response = error(200010);
                break;
            }


            $this->load->model('direct_seeding/Model_direct_seeding', 'ds');
            $item = $this->ds->getById($ds_id);
            if (empty($item))
            {
                $response = error(120002);
                break;
            }


            $where = array
            (
                'aid'     => $item['aid'],
                'is_thaw' => FINANCE_IS_THAW_NO,
            );
            $this->load->model('auction/Model_auction_log', 'al');
            $high_offer = $this->al->getOne($where, '*', 'lid desc');
            if (empty($high_offer))
            {
                $response = error(60055);
                break;
            }


            //解冻竞拍金额
            $this->load->model('finance/Model_finance_base_log', 'fbl');
            $thaw_rs = $this->fbl->thaw($high_offer['uid'], $high_offer['lid'], FINANCE_BUSINESS_AUCTION, 'THAW_AUCTION', '解冻_竞拍');
            if (200 != $thaw_rs['status'])
            {
                $thaw_rs['data']['is_consult'] = DIRECT_SEEDING_QUIT_STATUS_CONSULT;
                $response = error($thaw_rs['status']);
                break;
            }

            //解冻竞拍日志
            $al_thaw_rs = $this->al->thaw($high_offer['lid']);
            if (200 != $al_thaw_rs['status'])
            {
                $al_thaw_rs['data']['is_consult'] = DIRECT_SEEDING_QUIT_STATUS_CONSULT;
                $response = error($al_thaw_rs['status']);
                break;
            }


            //扣除用户竞拍金额
            $this->load->model('finance/Model_finance_base_log', 'fbl');
            $defray_rs = $this->fbl->defray
            (
                $high_offer['uid'],
                $high_offer['amount'],
                CURRENCY_SGD,
                $high_offer['lid'],
                '竞拍支出',
                'DEFRAY_AUCTION',
                FINANCE_BUSINESS_AUCTION,
                $high_offer['uname'].'竞拍 支出'
            );


            if (200 != $defray_rs['status'])
            {
                $defray_rs['data']['is_consult'] = DIRECT_SEEDING_QUIT_STATUS_CONSULT;
                $response = error($defray_rs['status']);
                break;
            }


            //解冻门票及结算门票
            $this->load->service('direct_seeding/service_direct_seeding_ticket');
            $settlement_rs = $this->service_direct_seeding_ticket->settlement($high_offer['aid']);

            if (200 != $settlement_rs['status'])
            {
                $settlement_rs['data']['is_consult'] = DIRECT_SEEDING_QUIT_STATUS_CONSULT;
                $response = error($settlement_rs['status']);
                break;
            }


            // 分配费用
            $grant_param = array
            (
                'type'    => DISTRIBUTION_AUCTION,
                'uid'     => $item['anchor_uid'],
                'bid'     => $high_offer['lid'],
                'b_title' => '竞拍',
                'amount'  => $high_offer['amount'],
            );

            $this->load->service('distribution/service_distribution_base');
            $grant_data = $this->service_distribution_base->grant($grant_param);

            if (200 != $grant_data['status'])
            {
                $grant_data['data']['is_consult'] = DIRECT_SEEDING_QUIT_STATUS_CONSULT;
                $response = error($grant_data['status']);
                break;
            }


            $save_rs = $this->ds->save(array('status' => DS_STATUS_YES), $ds_id);
            if (!$save_rs)
            {
                $response = error(100005);
                break;
            }

        }while (false);


        $this->json_output($response);
    }
}